package com.cjl.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cjl.auth.service.SysUserService;
import com.cjl.commons.exception.OAException;
import com.cjl.model.system.SysDept;
import com.cjl.auth.mapper.SysDeptMapper;
import com.cjl.auth.service.SysDeptService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cjl.model.system.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cjl.auth.utils.DeptHelper;

/**
 * <p>
 * 组织机构 服务实现类
 * </p>
 *
 * @author cjl
 * @since 2023-03-19
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public void updateStatus(Long id, Integer status) {
        baseMapper.updateStatus(id, status);
    }

    @Override
    public List<SysDept> getDeptList() {
        List<SysDept> sysDeptList = baseMapper.selectList(null);
        List<SysDept> resultList = DeptHelper.buildTree(sysDeptList);
        return resultList;
    }

    @Override
    public void removeDeptById(Long id) {
        LambdaQueryWrapper<SysDept> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDept::getParentId, id);
        Integer count = baseMapper.selectCount(wrapper);
        if(count > 0){
            throw new OAException(201, "存在子部门，不能删除");
        }
        baseMapper.deleteById(id);
    }

    @Override
    public Map<String, Object> findDeptByUserId(Long userId) {
        List<SysDept> sysDeptList = baseMapper.selectList(null);
        SysUser sysUser = sysUserService.getById(userId);
        Map<String, Object> map = new HashMap<>();
        map.put("deptList", sysDeptList);
        if(sysUser != null){
            map.put("deptId", sysUser.getDeptId());
        }
        return map;
    }
}
